/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aaron.platform.view;

import com.aaron.platform.dao.PageInfo;
import com.aaron.platform.entity.ItscDomainInfo;
import com.aaron.platform.entity.ItscRoleInfo;
import com.aaron.platform.entity.ItscUserInfo;
import com.aaron.platform.exceptions.DomainNotExistException;
import com.aaron.platform.exceptions.RoleNotExistException;
import com.aaron.platform.exceptions.UserAlreadyExistException;
import com.aaron.platform.exceptions.UserNotExistException;
import com.aaron.platform.service.IAuthorityService;
import com.aaron.platform.service.IDomainService;
import com.aaron.platform.service.IUserService;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.faces.model.SelectItem;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 *
 * @author mac
 */
public class UserListBean extends DataListBean {

    private static Logger logger = Logger.getLogger(UserListBean.class);

    private String userName;

    private Integer roleId;

    private String passWord;

    private String phoneNo;
    
    private String userChName;

    private String position;
    
    private Integer domainId;

    private IUserService userService;

    private IAuthorityService authorityService;

    private IDomainService domainService;

    public void setDomainService(IDomainService domainService) {
        this.domainService = domainService;
    }

    public void setAuthorityService(IAuthorityService authorityService) {
        this.authorityService = authorityService;
    }

    public UserListBean() {
        super();
        init();
        this.tableTitle = FacesUtil.getString("table_title_userlist");

        // 删除、编辑、查看操作
        this.deletable = true;
        this.editable = true;
        this.viewable = true;
        
        // 设置分页信息
        pagable = true;
    }

    private void init() {
        this.roleId = new Integer(0);
        this.userName = "";
        this.passWord = "";
        this.position = "";
        this.phoneNo = "";
        this.domainId = new Integer(0);
        pageInfo = new PageInfo<ItscUserInfo>();
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    public Integer getRoleId() {
        return roleId;
    }

    public void setRoleId(Integer roleId) {
        this.roleId = roleId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getPhoneNo() {
        return phoneNo;
    }

    public void setPhoneNo(String phoneNo) {
        this.phoneNo = phoneNo;
    }

    public String getUserChName() {
        return userChName;
    }

    public void setUserChName(String userChName) {
        this.userChName = userChName;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    public Integer getDomainId() {
        return domainId;
    }

    public void setDomainId(Integer domainId) {
        this.domainId = domainId;
    }

    public List<SelectItem> getRoleList() {
        List<ItscRoleInfo> roleInfos = authorityService.findAllRoles();
        List<SelectItem> items = new ArrayList<SelectItem>();
        items.add(new SelectItem(Integer.valueOf(0), "-"));
        for (ItscRoleInfo roleInfo : roleInfos) {
            items.add(new SelectItem(roleInfo.getRoleId(), roleInfo.getRoleName()));
        }
        return items;
    }

    /**
     * 获取所有域列表
     * @return 域列表
     */
    public List<SelectItem> getDomainList() {
        ItscDomainInfo domainInfo = domainService.findTopDomain();
        List<SelectItem> items = new ArrayList<SelectItem>();
        if (domainInfo != null) {
            addDomainList(items, domainInfo);
        }
        return items;
    }

    /**
     * 递归调用得到所有域
     * @param items 域显示列表
     * @param domainInfo 域信息
     */
    private void addDomainList(List<SelectItem> items,ItscDomainInfo domainInfo) {
        items.add(new SelectItem(domainInfo.getDomainId(), domainInfo.getDomainName()));
        for (ItscDomainInfo domain : domainInfo.getChildDomains()) {
            addDomainList(items, domain);
        }
    }

    @Override
    public void queryData() {
        Properties properties = new Properties();
        if (!StringUtils.isEmpty(userName)) {
            properties.setProperty(ItscUserInfo.PROPERTY_USER_NAME, StringUtils.trim(userName));
            
        } 
        if (roleId > 0) {
            properties.setProperty(ItscUserInfo.PROPERTY_USER_ROLEID, String.valueOf(roleId));
        }

        pageInfo = userService.findUsersByCondition(properties, pageInfo.getStartIndex(), pageInfo.getPageSize());
        logger.info("Query user list finished.");
        data.setWrappedData(pageInfo.getItems());
    }

    @Override
    public void initColumnHeaders() {
        headerColumns.add(new ColumnType(ColumnType.COLUMN_TEXT, "user_name", 
                FacesUtil.getString("table_column_username"), false, "10%"));
        headerColumns.add(new ColumnType(ColumnType.COLUMN_TEXT, "user_domain",
                FacesUtil.getString("table_column_userdomain"), false, "15%"));
        headerColumns.add(new ColumnType(ColumnType.COLUMN_TEXT, "user_role",
                FacesUtil.getString("table_column_role"), false, "15%"));
        headerColumns.add(new ColumnType(ColumnType.COLUMN_TEXT, "user_position",
                FacesUtil.getString("table_column_position"), false, "10%"));
        headerColumns.add(new ColumnType(ColumnType.COLUMN_TEXT, "user_phone",
                FacesUtil.getString("table_column_phone"), false, "15%"));
    }

    @Override
    public String getColumnValue() {
        String columnName = getColumnName();
        increaseColumnIndex();
        
        ItscUserInfo obj = (ItscUserInfo) data.getRowData();
        if (columnName.equals("user_position")) {
            return obj.getUserPosition();
        } else if (columnName.equals("user_name")) {
            return obj.getUserName();
        } else if (columnName.equals("user_domain")) {
            return obj.getDomainInfo().getDomainName();
        } else if (columnName.equals("user_role")) {
            return obj.getRoleInfo().getRoleName();
        } else if (columnName.equals("user_phone")) {
            return obj.getUserTelephone();
        } else {
            return null;
        }
    }

    @Override
    public String deleteData() {
        
        // 获取选择删除的用户，删除用户
        ItscUserInfo userInfo = (ItscUserInfo) data.getRowData();

        // 判断是否是当前用户，不允许自我删除
        UserloginBean loginBean = (UserloginBean) FacesUtil.getManagedBean("userLoginBean");
        if (userInfo.getUserName().equals(loginBean.getCurrentUserInfo().getUserName())) {
            FacesUtil.addErrorMessage(null, "warn_delete_self");
            return null;
        }
        try {
            userService.removeUser(userInfo.getUserId());
        } catch (UserNotExistException ex) {
            logger.error("user: " + userInfo.getUserName() + " does not exist.");
            FacesUtil.addErrorMessage(null, ex.getErrorCode(), userInfo.getUserName());
            return null;
        }
        FacesUtil.addInfoMessage(null, "in_user_deleted", userInfo.getUserName());
        
        // 刷新页面
        return null;
    }

    /**
     * 导航到用户添加页面
     * @return 用户添加页面
     */
    public String toAddUser() {

        // 初始化
        init();

        return "user_add";
    }

    public String addUser() {

        if (this.roleId == 0) {
            FacesUtil.addErrorMessage("userAddForm:roles", "er_user_role_required");
            return null;
        }

        // 查询角色信息
        ItscRoleInfo roleInfo = null;
        try {
            roleInfo = authorityService.findRoleById(roleId);
        } catch (RoleNotExistException ex) {
            logger.error("Role (ID:" + roleId + ") does not exist.");
            FacesUtil.addErrorMessage(null, ex.getErrorCode(), roleId);
            return null;
        }

        // 查询域信息
        ItscDomainInfo domainInfo = null;
        try {
            domainInfo = domainService.findById(domainId);
        } catch (DomainNotExistException ex) {
            logger.error("Domain (ID:" + domainId + ") does not exist.");
            FacesUtil.addErrorMessage(null, ex.getErrorCode(), domainId);
            return null;
        }

        // 构造用户信息
        ItscUserInfo userInfo = new ItscUserInfo();
        userInfo.setUserName(userName);
        userInfo.setUserPwd(passWord);
        userInfo.setUserPosition(position);
        userInfo.setUserTelephone(phoneNo);
        userInfo.setUserChName(userChName);
        userInfo.setRoleInfo(roleInfo);
        userInfo.setDomainInfo(domainInfo);

        try {
            // 添加用户
            userService.addUser(userInfo);
        } catch (UserAlreadyExistException ex) {
            logger.error("User " + userName + " has already existed.");
            FacesUtil.addErrorMessage(null, ex.getErrorCode(), userName);
            return null;
        }

        logger.debug("User " + userName + " has been added successfully.");
        FacesUtil.addInfoMessage(null, "in_user_added", userName);

        // 初始化页面信息，返回用户管理页面
        init();
        return "user_management";
    }

}
